<template>
  <div class="detail-container">
    <a-spin :spinning="loading">
      <div class="detail-header">
        <!-- <a-button type="link" @click="goBack" class="back-btn">
          <template #icon>
            <ArrowLeftOutlined />
          </template>
          返回
        </a-button> -->
        <h2>设备详情</h2>
      </div>
     <div class="detail-wrapper">
    <div class="detail-main">
      <div class="detail-column">
        <div class="column-title">设备信息</div>
        <div class="column-content">
          <a-descriptions
            bordered
            :labelStyle="{ width: '120px' }"
            :contentStyle="{ width: '500px' }"
            :column="{ xxl: 2, xl: 2, lg: 2, md: 1, sm: 1, xs: 1 }"
          >
            <a-descriptions-item label="设备ID"
              >{{ deviceData.device_id }}</a-descriptions-item
            >
            <a-descriptions-item label="设备状态ID">
              {{ deviceData.device_status_id }}
            </a-descriptions-item>
            <a-descriptions-item label="设备名称"
              >{{ deviceData.name }}</a-descriptions-item
            >
            <a-descriptions-item label="客户名称"
              >客户名称</a-descriptions-item
            >
            <a-descriptions-item label="经销商"
              >经销商</a-descriptions-item
            >
            <a-descriptions-item label="设备在线状态"
              >使用中</a-descriptions-item
            >
            <a-descriptions-item label="设备序列号">
              {{ deviceData.sn }}
            </a-descriptions-item>
            <a-descriptions-item label="保修期月数">
              {{ deviceData.warranty_month }}个月
            </a-descriptions-item>
            <a-descriptions-item label="设备型号">{{ deviceData.model_number }}</a-descriptions-item>
            <a-descriptions-item label="软件版本"
              >{{ deviceData.app_version }}</a-descriptions-item
            >
            <a-descriptions-item label="备注">
              {{ deviceData.remark || '无' }}
            </a-descriptions-item>
            <a-descriptions-item label="创建时间">
              {{ deviceData.created }}
            </a-descriptions-item>
            <a-descriptions-item label="更新时间">
              {{ deviceData.updated }}
            </a-descriptions-item>
          </a-descriptions>
        </div>
      </div>
      <div class="detail-column">
        <div class="column-title">设备模型文件</div>
        <div class="column-content">
          <div v-if="deviceData.model_files_list && deviceData.model_files_list.length > 0">
            <div v-for="(file, index) in deviceData.model_files_list" :key="index" class="file-item">
              {{ file.name || `模型文件${index + 1}` }}
              <a-button :icon="h(DownloadOutlined)" type="primary" size="small" style="margin-left: 8px;">下载</a-button>
            </div>
          </div>
          <div v-else>暂无模型文件</div>
        </div>
      </div>
      <div class="detail-column">
        <div class="column-title">预览图片文件</div>
        <div class="column-content">
          <div v-if="deviceData.image_files_list && deviceData.image_files_list.length > 0">
            <div v-for="(file, index) in deviceData.image_files_list" :key="index" class="file-item">
              <img v-if="file.url" :src="file.url" alt="预览图" style="max-width: 200px; max-height: 150px; margin-right: 8px;" />
              <div>
                {{ file.name || `图片文件${index + 1}` }}
                <a-button :icon="h(DownloadOutlined)" type="primary" size="small" style="margin-left: 8px;">下载</a-button>
              </div>
            </div>
          </div>
          <div v-else>暂无图片文件</div>
        </div>
      </div>
      <div class="detail-column">
        <div class="column-title">仪器介绍</div>
        <div class="column-text" v-html="deviceData.introduce">
        </div>
      </div>
      <div class="detail-column">
        <div class="column-title">实验内容</div>
        <div class="column-text" v-html="deviceData.experiments">
        </div>
      </div>
      <div class="detail-column">
        <div class="column-title">配置参数</div>
        <div class="column-content">
          <a-descriptions
            bordered
            :labelStyle="{ width: '120px' }"
            :contentStyle="{ width: '500px' }"
            :column="{ xxl: 3, xl: 3, lg: 3, md: 1, sm: 1, xs: 1 }"
            v-if="deviceData.device_param_list && deviceData.device_param_list.length > 0"
          >
            <template v-for="(config,key) in deviceData.device_param_list" :key="key">
               <a-descriptions-item :label="config.param_key">{{ config.param_value }}</a-descriptions-item>
             </template>
          </a-descriptions>
          <div v-else>暂无配置参数</div>
        </div>
      </div>
      <!-- <div class="detail-column" v-if="deviceData.url_report_repair">
        <div class="column-title">报修二维码</div>
        <div class="column-content">
          <div class="qr-code-container">
            <div v-if="qrCodeDataUrl && !qrCodeError" class="qr-code-success">
              <img 
                :src="qrCodeDataUrl" 
                alt="报修二维码" 
                style="max-width: 200px; max-height: 200px; display: block; margin-bottom: 10px; border: 1px solid #d9d9d9; border-radius: 4px;" 
              />
              <div style="font-size: 12px; color: #52c41a; margin-bottom: 8px;">✓ 二维码已生成</div>
              <a-button @click="downloadQRCode" type="primary" size="small" style="margin-bottom: 8px;">
                <template #icon>
                  <DownloadOutlined />
                </template>
                下载二维码
              </a-button>
            </div>
            <div v-else-if="qrCodeError" class="qr-code-error">
              <div style="padding: 20px; text-align: center; color: #999; border: 1px dashed #d9d9d9; border-radius: 4px;">
                <div>二维码生成失败</div>
                <div style="font-size: 12px; margin-top: 5px;">请检查报修链接是否有效</div>
              </div>
            </div>
            <div v-else class="qr-code-loading">
              <div style="padding: 20px; text-align: center; color: #1890ff; border: 1px solid #d9d9d9; border-radius: 4px;">
                <div>正在生成二维码...</div>
              </div>
            </div>
            <p style="word-break: break-all; color: #666; font-size: 12px; margin-top: 8px;">报修链接：{{ deviceData.url_report_repair }}</p>
          </div>
        </div>
      </div> -->
    </div>
    </div>
    </a-spin>
  </div>
</template>
<script setup>
import { ref, computed, h, onMounted, nextTick } from "vue";
import { DownloadOutlined, ArrowLeftOutlined } from "@ant-design/icons-vue";
import { useRoute } from "vue-router";
import { message } from "ant-design-vue";
import API from "@/api/operation";
import QRCode from "qrcode";

// 下载二维码函数
const downloadQRCode = () => {
  if (qrCodeDataUrl.value) {
    const link = document.createElement('a');
    link.href = qrCodeDataUrl.value;
    link.download = `设备${deviceData.value.name || deviceData.value.device_id}_报修二维码.png`;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    message.success('二维码下载成功');
  } else {
    message.error('二维码未生成，无法下载');
  }
};
const route = useRoute();
const query = computed(() => route.query);
const loading = ref(false);
const qrCodeError = ref(false);
const qrCodeDataUrl = ref('');

// const goBack = () => {
//   router.go(-1);
// };

// 二维码加载成功处理
const onQrCodeLoad = () => {
  qrCodeError.value = false;
};

// 二维码加载失败处理
const onQrCodeError = () => {
  qrCodeError.value = true;
  console.error('二维码图片加载失败:', deviceData.value.url_report_repair);
};

// 生成二维码
const generateQRCode = async (url) => {
  try {
    if (!url) {
      qrCodeError.value = true;
      return;
    }
    
    const qrCodeUrl = await QRCode.toDataURL(url, {
      width: 200,
      margin: 2,
      color: {
        dark: '#000000',
        light: '#FFFFFF'
      }
    });
    
    qrCodeDataUrl.value = qrCodeUrl;
    qrCodeError.value = false;
  } catch (error) {
    console.error('生成二维码失败:', error);
    qrCodeError.value = true;
  }
};
const deviceData = ref({
  device_id: "",
  device_status_id: null,
  name: "",
  sn: "",
  warranty_month: null,
  model_number: "",
  app_version: "",
  introduce: "",
  experiments: "",
  remark: "",
  created: "",
  updated: "",
  deleted: false,
  model_files_list: [],
  image_files_list: [],
  device_param_list: [],
  url_report_repair: ""
});

// 获取设备详情
const getDeviceDetail = async (deviceId) => {

  try {
    loading.value = true;
    qrCodeError.value = false; // 重置二维码错误状态
    // 调用DeviceFetchModel接口获取设备详情
    const response = await API.DeviceFetchModel({ device_id: deviceId });
    if (response) {

      const data = response;
      deviceData.value = {
        device_id: data.device_id || "",
        device_status_id: data.device_status_id || null,
        name: data.name || "",
        sn: data.sn || "",
        warranty_month: data.warranty_month || null,
        model_number: data.model_number || "",
        app_version: data.app_version || "",
        introduce: data.introduce || "",
        experiments: data.experiments || "",
        remark: data.remark || "",
        created: data.created || "",
        updated: data.updated || "",
        deleted: data.deleted || false,
        model_files_list: data.model_files_list || [],
        image_files_list: data.image_files_list || [],
        device_param_list: data.device_param_list || [],
        url_report_repair: data.url_report_repair || ""
      };
      console.log('设备详情:', deviceData.value)
      
      // 如果有报修URL，生成二维码
      if (data.url_report_repair) {
        await nextTick();
        generateQRCode(data.url_report_repair);
      }
    } else {
      message.error('获取设备详情失败');
    }
  } catch (error) {
    console.error('获取设备详情失败:', error);
    message.error('获取设备详情失败');
  } finally {
    loading.value = false;
  }
};

onMounted(() => {

  console.log(query.value.id)
  if (query.value.id) {

    getDeviceDetail(query.value.id);
  }
});
</script>

